package com.zadtek.shopmall.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.zadtek.shopmall.Event.EventPoiAddress;
import com.zadtek.shopmall.Event.EventUpdateAddressList;
import com.zadtek.shopmall.R;
import com.zadtek.shopmall.base.AbsActivity;
import com.zadtek.shopmall.bean.AddressItem;
import com.zadtek.shopmall.bean.OperateResponseBean3;
import com.zadtek.shopmall.net.BaseObserver;
import com.zadtek.shopmall.net.BaseResponse;
import com.zadtek.shopmall.net.NetTool;
import com.zadtek.shopmall.utils.ToastUtil;
import com.zadtek.shopmall.view.SpacesItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class AddressListActivity extends AbsActivity {
    private ImageView ivBack;
    private TextView topTitle,tvAddAddress;
    private RecyclerView recyclerView;
    private List<AddressItem> data = new LinkedList<>();
    private AddressAdapter adapter;
    private int page =1;
    private int pagesize = 10;
    @Override
    public int setView() {
        return R.layout.activity_address_list;
    }

    @Override
    public void initBasic(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        initView();
        initLogic();
        requestData();
    }

    private void initView() {
        ivBack = (ImageView) findViewById(R.id.ic_back);
        ivBack.setVisibility(View.VISIBLE);
        topTitle = (TextView) findViewById(R.id.title);
        topTitle.setText("地址管理");
        tvAddAddress = (TextView) findViewById(R.id.tv_add_address);
        recyclerView = (RecyclerView)findViewById(R.id.recycleview);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.addItemDecoration(new SpacesItemDecoration(getResources().getDimensionPixelSize(R.dimen.little_margin)));
    }

    private void initLogic(){
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tvAddAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addNewAddress();
            }
        });
        adapter = new AddressAdapter(R.layout.address_item,data);
        recyclerView.setAdapter(adapter);
        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                requestData();
            }
        },recyclerView);
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()){
                    case R.id.tv_name:
                        break;
                    case R.id.tv_phonenumber:
                        break;
                    case R.id.tv_address:
                        break;
                    case R.id.cb_default:
                        chooseDefault(position);
                        break;
                    case R.id.tv_edit:
                        startActivity(new Intent(AddressListActivity.this,EditAddressActivity.class).putExtra("addressitem",data.get(position)));
                        break;
                    case R.id.tv_delete:
                        delAddress(position);
                        break;
                }
            }
        });
    }

    private void delAddress(final int position) {
        Map<String, Object> para = NetTool.newParams();
        para.put("address_id",data.get(position).getAddress_id());
        NetTool.getApi().delAddress(para).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<OperateResponseBean3>>(this) {
                    @Override
                    public void onData(BaseResponse<OperateResponseBean3> value) {
                        if(value.getCode()==0 && value.getData()!=null){
                            if(value.getData().isSuccess()){
                                data.remove(position);
                                adapter.notifyDataSetChanged();
                            }
                        }
                    }
                });
    }

    private void chooseDefault(final int position) {
        for(AddressItem item:data){
            item.setDefault(false);
        }
        Map<String, Object> para = NetTool.newParams();
        para.put("address_id",data.get(position).getAddress_id());
        NetTool.getApi().defaultAddress(para).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<OperateResponseBean3>>(this) {
                    @Override
                    public void onData(BaseResponse<OperateResponseBean3> value) {
                        if(value.getCode()==0 && value.getData()!=null){
                            if(value.getData().isSuccess()){
                                data.get(position).setDefault(true);
                                adapter.notifyDataSetChanged();
                            }
                        }
                    }
                });
    }

    private void requestData() {
        NetTool.getApi().getAddressList(NetTool.newParams()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                .subscribe(new BaseObserver<BaseResponse<List<AddressItem>>>(this) {
                    @Override
                    public void onData(BaseResponse<List<AddressItem>> value) {
                        if(value.getCode() == 0 && value.getData()!=null){
                            data.addAll(value.getData());
                            adapter.notifyDataSetChanged();
                            adapter.loadMoreEnd();
                        }else{

                        }
                    }
                });

    }


    private void addNewAddress() {
        startActivity(new Intent(this,EditAddressActivity.class));
        ToastUtil.showToast("添加新地址请求！");
    }

    private class AddressAdapter extends BaseQuickAdapter<AddressItem,BaseViewHolder> {
        public AddressAdapter(int layoutResId, @Nullable List<AddressItem> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, AddressItem item) {
            if(item.isDefault()){
                helper.setChecked(R.id.cb_default,true);
            }else{
                helper.setChecked(R.id.cb_default,false);
            }
            helper.setText(R.id.tv_name,item.getConsignee());
            helper.setText(R.id.tv_phonenumber,item.getMobile());
            helper.setText(R.id.tv_address,item.getArea()+item.getAddress());
            helper.addOnClickListener(R.id.cb_default);
            helper.addOnClickListener(R.id.tv_edit);
            helper.addOnClickListener(R.id.tv_delete);
        }
    }

    @Subscribe
    public void onEventMainThread(EventUpdateAddressList event) {
        data.clear();
        requestData();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
